/*
 * Copyright (C) 2020, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <QTime>
#include <QDesktopServices>
#include <QUrl>
#include <QPainter>
#include "menumodule.h"
#include "xatom-helper.h"

menuModule::menuModule(QWidget *parent = nullptr) : QWidget(parent)
{
    init();
}

void menuModule::init()
{
    initAction();
}

void menuModule::initAction()
{
    QFont ft;
    ft.setPixelSize(14);
    m_bodySupport = new QLabel();
    m_titleText = new QLabel();
    m_bodyAppName = new QLabel();
    m_bodyAppVersion = new QLabel();

    m_menuButton = new QToolButton(this);
    m_menuButton->setProperty("isWindowButton", 0x1);
    m_menuButton->setProperty("useIconHighlightEffect", 0x2);
    m_menuButton->setPopupMode(QToolButton::InstantPopup);
    m_menuButton->setFixedSize(30,30);
    m_menuButton->setIconSize(QSize(16, 16));
    m_menuButton->setAutoRaise(true);
    m_menuButton->setIcon(QIcon::fromTheme("open-menu-symbolic"));

    m_menu = new QMenu(this);
//    m_menu->setFont(ft);
    QList<QAction *> actions ;
    QAction *actionStandard = new QAction(m_menu);
    actionStandard->setText(tr("standard"));
    QAction *actionScientific = new QAction(m_menu);
    actionScientific->setText(tr("scientific"));
    QAction *actionExchangeRate = new QAction(m_menu);
    actionExchangeRate->setText(tr("exchange rate"));

    QAction *separator = new QAction(m_menu);
    separator->setSeparator(true);

    QAction *actionTheme = new QAction(m_menu);
    actionTheme->setText(tr("Theme"));
    QAction *actionHelp = new QAction(m_menu);
    actionHelp->setText(tr("Help"));
    QAction *actionAbout = new QAction(m_menu);
    actionAbout->setText(tr("About"));
    QAction *actionQuit = new QAction(m_menu);
    actionQuit->setText(tr("Quit"));
    actions // << actionTheme
            << actionHelp
            << actionAbout
            << actionQuit;

    m_menu->addActions(actions);

    m_menuButton->setMenu(m_menu);
    connect(m_menu,&QMenu::triggered,this,&menuModule::triggerMenu);
}

void menuModule::triggerMenu(QAction *act)
{
    QString str = act->text();
    if(tr("Quit") == str){
        emit menuModuleClose();
    }
    else if(tr("About") == str){
        aboutAction();
    }
    else if(tr("Help") == str){
        helpAction();
    }
}

void menuModule::aboutAction()
{
//    关于点击事件处理
    if (m_aboutWindow != nullptr) {
        m_aboutWindow->hide();
        
        QTime dieTime = QTime::currentTime().addMSecs(50);
        while( QTime::currentTime() < dieTime )
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

        QPoint temp = QPoint(this->parentWidget()->mapToGlobal(QPoint(0,0)).x() + this->parentWidget()->width()/2,this->parentWidget()->mapToGlobal(QPoint(0,0)).y() + this->parentWidget()->height()/2 -40);
        m_aboutWindow->move(temp - m_aboutWindow->rect().center());
        m_aboutWindow->show();
        // aboutWindow->activateWindow();
        return ;
    }
    initAbout();
}

void menuModule::helpAction()
{
//    帮助点击事件处理

    DaemonIpcDbus *ipcDbus = new DaemonIpcDbus();
    if(!ipcDbus->daemonIsNotRunning()){
        ipcDbus->showGuide(m_appName);
    }
    ipcDbus->deleteLater();
}

void menuModule::initAbout()
{
    m_aboutWindow = new kdk::KAboutDialog(this,QIcon::fromTheme("kylin-service-support"),tr("Service and Support"),tr("version: ") + APP_VERSION);
    m_aboutWindow->setBodyText("关于对话框，包含的主要内容有：应用图标，应用名称，版本号，团队邮箱以及具体的应用描述，注意，默认应用描述是不显示的。");
    m_aboutWindow->setBodyTextVisiable(false);
    m_aboutWindow->setWindowModality(Qt::WindowModal);
    m_aboutWindow->setWindowModality(Qt::ApplicationModal);

    m_aboutWindow->exec();
}

QHBoxLayout* menuModule::initTitleBar()
{
    m_titleIconBtn = new QPushButton();
    m_titleIconBtn->setIcon(QIcon::fromTheme("kylin-service-support"));
    m_titleIconBtn->setIconSize(QSize(24,24));
    m_titleIconBtn->setFixedSize(QSize(24,24));
    QString btnStyle = "QPushButton{border:0px;border-radius:4px;background:transparent;}"
                       "QPushButton:Hover{border:0px;border-radius:4px;background:transparent;}"
                       "QPushButton:Pressed{border:0px;border-radius:4px;background:transparent;}";
    m_titleIconBtn->setStyleSheet(btnStyle);



    QPushButton *titleBtnClose = new QPushButton;
    titleBtnClose->setFixedSize(30,30);
    titleBtnClose->setIcon(QIcon::fromTheme("window-close-symbolic"));
    titleBtnClose->setProperty("isWindowButton",0x2);
    titleBtnClose->setProperty("useIconHighlightEffect",0x8);
    titleBtnClose->setFlat(true);
    connect(titleBtnClose,&QPushButton::clicked,[=](){m_aboutWindow->close();});
    
    m_titleText->setText(tr(m_appShowingName.toLocal8Bit()));
    
    QHBoxLayout *hlyt = new QHBoxLayout;
    hlyt->setSpacing(0);
    hlyt->setContentsMargins(4,4,4,4);
    hlyt->addSpacing(4);
    hlyt->addWidget(m_titleIconBtn); //居下显示
    hlyt->addSpacing(8);
    hlyt->addWidget(m_titleText);
    hlyt->addStretch();
    hlyt->addWidget(titleBtnClose);

    return hlyt;
}

QVBoxLayout* menuModule::initBody()
{
    m_bodyIcon = new QPushButton();
    m_bodyIcon->setIcon(QIcon::fromTheme("kylin-service-support"));
    m_bodyIcon->setIconSize(QSize(96,96));
    m_bodyIcon->setFixedSize(QSize(96,96));
    QString btnStyle = "QPushButton{border:0px;border-radius:4px;background:transparent;}"
                        "QPushButton:Hover{border:0px;border-radius:4px;background:transparent;}"
                        "QPushButton:Pressed{border:0px;border-radius:4px;background:transparent;}";
    m_bodyIcon->setStyleSheet(btnStyle);


    m_bodyAppName->setText(tr(m_appShowingName.toLocal8Bit()));

    m_bodyAppVersion->setText(tr("Version: ") + m_appVersion);
    m_bodyAppVersion->setAlignment(Qt::AlignLeft);

    connect(m_bodySupport,&QLabel::linkActivated,this,[=](const QString url){
        QDesktopServices::openUrl(QUrl(url));
    });
    m_bodySupport->setContextMenuPolicy(Qt::NoContextMenu);
    m_bodySupport->setObjectName("bodySupport");

    if("ukui-dark" == m_currentStyle || "ukui-black" == m_currentStyle)
    {
        m_bodySupport->setText(tr("Service & Support: ") +
                             "<a href=\"mailto://support@kylinos.cn\""
                             "style=\"color:rgba(225,225,225,1)\">"
                             "support@kylinos.cn</a>");
    }
    else
    {
        m_bodySupport->setText(tr("Service & Support: ") +
                             "<a href=\"mailto://support@kylinos.cn\""
                             "style=\"color:rgba(0,0,0,1)\">"
                             "support@kylinos.cn</a>");
    }

    QVBoxLayout *vlyt = new QVBoxLayout;
    vlyt->setMargin(0);
    vlyt->setSpacing(0);
    vlyt->addSpacing(20);
    vlyt->addWidget(m_bodyIcon,0,Qt::AlignHCenter);
    vlyt->addSpacing(16);
    vlyt->addWidget(m_bodyAppName,0,Qt::AlignHCenter);
    vlyt->addSpacing(12);
    vlyt->addWidget(m_bodyAppVersion,0,Qt::AlignHCenter);
    vlyt->addSpacing(12);
    vlyt->addWidget(m_bodySupport,0,Qt::AlignHCenter);
    vlyt->addStretch();
    return vlyt;
}

void menuModule::changeFont(QFont curFont)
{
    m_menu->setFont(curFont);
    m_titleText->setFont(curFont);
    m_bodyAppVersion->setFont(curFont);
    m_bodySupport->setFont(curFont);

    double appNameFontSize = (static_cast<double>(curFont.pointSizeF())/14)*18;
    QFont appNameFont;
    appNameFont.setPointSizeF(appNameFontSize);

    m_bodyAppName->setFont(appNameFont);
}

void menuModule::changePageForTheme(const QString& str)
{
    m_currentStyle = str;
    if("ukui-dark" == str || "ukui-black" == str)
    {
        m_bodySupport->setText(tr("Service & Support: ") +
                             "<a href=\"mailto://support@kylinos.cn\""
                             "style=\"color:rgba(225,225,225,1)\">"
                             "support@kylinos.cn</a>");
    }
    else
    {
        m_bodySupport->setText(tr("Service & Support: ") +
                             "<a href=\"mailto://support@kylinos.cn\""
                             "style=\"color:rgba(0,0,0,1)\">"
                             "support@kylinos.cn</a>");
    }
}

bool menuModule::hasAboutWindow()
{
    return m_aboutWindow != nullptr;
}

void menuModule::closeAboutWindow()
{
    m_aboutWindow->close();
}

QToolButton * menuModule::getMenuBtn()
{
    return m_menuButton;
}
